﻿using UnityEngine;
using System.Collections;

public class Ship : MonoBehaviour {

    public float thrust;    //Forward acceleration.
    public float rotateSpeed;   //Rotation acceleration / torque.
    public float angularDamping;    //The rate at which the players spin is killed.

    private bool isLanded = true;   //Controls disabled when landed.
    private bool canLand = true;
    private bool isCrashed = false;

    private Body bodyOrbiting;  //The body the ship is currently orbiting. (The sun if no other planet).
    private Vector2 forceFromBodyOrbiting;  //The gravitational force applied to this ship from the body it is orbiting.

    void Start() {
        bodyOrbiting = GameObject.Find("Sun").GetComponent<Body>(); //Start by orbiting the sun by default.
    }

    void FixedUpdate()
    {
        if (!isLanded) {
            //Keyboard controls.
            if (Input.GetKey(KeyCode.UpArrow)) {
                rigidbody2D.AddForce(transform.up * thrust * Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.LeftArrow)) {
                rigidbody2D.AddTorque(Time.deltaTime * rotateSpeed);
            } else if (Input.GetKey(KeyCode.RightArrow)) {
                rigidbody2D.AddTorque(Time.deltaTime * -rotateSpeed);
            } else if (rigidbody2D.angularVelocity > 0.1f || rigidbody2D.angularVelocity < 0.1f) {  //If no rotation is applied then kill the current rotation smoothly.
                rigidbody2D.AddTorque(Time.deltaTime * -rigidbody2D.angularVelocity * angularDamping);  //Add torque in the opposite direction to that we are spinning.
            } else {
                rigidbody2D.angularVelocity = 0f;   //If there is practically 0 angular velocity then set it equal to 0.
            }
            forceFromBodyOrbiting = (bodyOrbiting.transform.position - transform.position).normalized * (1 / Mathf.Abs((bodyOrbiting.transform.position - transform.position).sqrMagnitude)) * bodyOrbiting.gravityStrength;
            //Gravity calculation: Gravity force = (direction * (1 / distance from centre^2) * gravity strength).
            if (forceFromBodyOrbiting.magnitude < bodyOrbiting.minimumGravitationalForce) { //If the force is too weak (below minimum force for the body we are orbiting) then set the force equal to the minimum required force.
                Vector3.Normalize(forceFromBodyOrbiting);
                forceFromBodyOrbiting *= bodyOrbiting.minimumGravitationalForce;
            }
            rigidbody2D.AddForce(forceFromBodyOrbiting);    //Apply the force to the ship.
        } else {
            //If we are landed check if we want to take off.
            if (Input.GetKey(KeyCode.Space)) {
                isLanded = false;
                rigidbody2D.AddForce(transform.up * thrust * Time.deltaTime);
                this.transform.parent = null;
            }
        }
    }

    void OnCollisionEnter2D(Collision2D col) {
       if(col.gameObject.tag == "Planet") { //If we collide with a planet we have landed there, no matter how hard we hit it!
            if (canLand)
            {
                isLanded = true;
                this.transform.parent = col.gameObject.transform;
            }
        }
    }

    void OnTriggerStay2D(Collider2D col) {
        bodyOrbiting = col.GetComponentInParent<Planet>();  //Whilst within a SoI, get the body we are orbiting.
        /*if (col.gameObject.tag == "Planet") {
            Debug.Log("Giggity");
            this.transform.parent = col.gameObject.transform;
        }*/
    }

    void OnTriggerExit2D(Collider2D col) {
        bodyOrbiting = GameObject.Find("Sun").GetComponent<Body>(); //If we leave an SoI, make the sun the body we orbit.
        /*if (col.gameObject.tag == "Planet")
        {
            Debug.Log("Giggity");
            this.transform.parent = col.gameObject.transform;
        }*/
    }
}
